#pragma once

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string>
#include <cstring>
#include <cstdlib>
#include <memory>
#include <functional>

#include "Logger.hpp"
#include "InetAddr.hpp"
#include "ThreadPool.hpp"


static const int sockfdDefault = -1;

using callback_t = std::function<void(int sockfd, std::string message, InetAddr addr)>;

class ChatServer
{
public:
    ChatServer(uint16_t port, callback_t cb)
        :_port(port)
        ,_is_running(false)
        ,_sockfd(sockfdDefault)
        ,_cb(cb)
    {}

    void Init()
    {
        //1、创建套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);//前两个参数已经能够表明我们创建的是udp套接字了，所以第三个参数传0即可
        if(_sockfd < 0)
        {
            LOG(Loglevel::FATAL) << "create socket error";
            exit(1);
        }
        LOG(Loglevel::INFO) << "create socket success : " << _sockfd;

        //2、填充sockaddr_in结构体（套接字是以结构体的形式进行保存和管理的）
        InetAddr local(_port);
        

        //3、使用bind将套接字与服务端进行绑定
        int n = bind(_sockfd, (struct sockaddr*)&local, sizeof(local));
        if(n < 0)
        {
            LOG(Loglevel::FATAL) << "bind socket error";
            exit(2);
        }
        LOG(Loglevel::INFO) << "bind socket success : " << _sockfd;
    }

    void Start()
    {
        _is_running = true;
        while(true)
        {
            struct sockaddr_in peer;
            char buffer[1024];
            buffer[0] = 0;//清空字符数组
            socklen_t peerlen = sizeof(peer);
            //获取收到的信息
            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer), 0, (struct sockaddr*)&peer, &peerlen);
            
            if(n > 0)
            {
                buffer[n] = 0;
                InetAddr clientaddr(peer);
                LOG(Loglevel::DEBUG) <<  "get a client info # " 
                    << clientaddr.Ip() << "-" << clientaddr.Port() << ": "
                    << buffer;
                std::string message = buffer;
                _cb(_sockfd, message, clientaddr);
            }
        }
        _is_running = false;
    }

    void Stop()
    {
        _is_running = false;
    }

    ~ChatServer()
    {}
    
private:
    int _sockfd;
    uint16_t _port;
    bool _is_running;
    callback_t _cb;
};
